package com.ds.infrastructure.audit.collector.security;

import com.ds.infrastructure.audit.collector.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/10
 */
@Slf4j
public class SsoAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final AuthenticationManager authenticationManager;

    public SsoAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher("/**"));
        this.authenticationManager = authenticationManager;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //String sid = request.getHeader(CommonConstant.HTTP_HEADER_AUTHORIZATION);
        String sid = RequestUtils.getAuthorization(request);
        log.debug("sid={}", sid);
        SidAuthenticationToken authRequest = new SidAuthenticationToken(sid);
        return authenticationManager.authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    }
}
